<?php
/**
 * Zend_Db_Table_Row_Abstract based class implementing the
 * <a href="http://www.martinfowler.com/eaaCatalog/tableDataGateway.html">Table Data Gateway pattern</a>
 * to access tables
 *
 * You can instantiate a class extending BaseRow and save it. Note that the defaults values defined in the database
 * schema is used to fill empty object
 *
 * @see Application
 */
abstract class BaseRow extends Zend_Db_Table_Row_Abstract
{
    /**
     * Constructor.
     *
     * Supported params for $config are:
     * - table       = class name or object of type Zend_Db_Table_Abstract
     * - data        = values of columns in this row.
     *
     * @param array $config OPTIONAL Array of user-specified config options.
     * @return void
     * @throws Zend_Db_Table_Row_Exception
     */

    function __construct(array $config = array())
    {
        // If no _tableClass is defined, let's go for the xxxxTable convention
        if (!$this->_tableClass)
            $this->_tableClass = (get_class($this) == 'BaseRow' ? 'Base' : get_class($this)) . 'Table';

        parent::__construct($config);

        // The following allows to set the _data array, allowing a new BaseRow()
        // get information about the columns
        $cols = $this->_table->info(Zend_Db_Table::COLS);
        $defaults = array_combine($cols, array_fill(0, count($cols), null));

        foreach ($this->_table->info(Zend_Db_Table::METADATA) as $metadataName => $metadata) {
            if (($metadata['DEFAULT'] != null)
                    &&
                    ($metadata['NULLABLE'] !== true ||
                            ($metadata['NULLABLE'] === true &&
                                    isset($defaultValues[$metadataName]) &&
                                    $defaultValues[$metadataName] === true))
                    &&
                    (!(isset($defaultValues[$metadataName]) && $defaultValues[$metadataName] === false))) {
                // Set the default value
                $defaults[$metadataName] = $metadata['DEFAULT'];
            }
        }

        if (isset($config['data']) && is_array($config['data'])) {
            $defaults = array_merge($defaults, $config['data']);
        }

        $this->_data = $defaults;
    }
}
